<?php
namespace Admin\Model;
use Think\Model;
/**
 * OM配置模型
 * 
 */

class CalllogModel extends Model{

  protected $log_types = array('0'=>'打入','1' =>'打出','2' => '呼叫转移入','3'=>'呼叫转移出','4'=>'内部通话','5'=>'双向外呼');


  //获取通话类型名
  public function getTypes(){
    $types = array();
    foreach( $this->log_types as $kv=>$vt ){
      $item = array('k'=>$kv,'v'=>$vt);
      $types[] = $item;
    }
    return $types;
  }

  // 获得所属部门以及其下属部门
   public function getchild(){
    	$uinfo = UserModel::loadFromSession();
    	$sectorid = $uinfo['sector_id'];
    	$sector =  M('sector');
    	$data = $sector->select();
    	return $this->getchildids($data,$sectorid);
   }


   public function getchildids($data,$sectorid){
      static $arrid=array();
      $arrid[]=$sectorid;
      foreach ($data as $key => $value) {
         if ($value['parent_sector'] == $sectorid && $value['sector_id'] !=  $sectorid) {//找子类
            $arrid[]=$value['sector_id'];
            $this->getchildids($data,$value['sector_id']);
         }
      }
      return array_unique($arrid);
   }


  // 获得所属部门以及其下属部门
   public function getchild1($sectorid){
      $sector =  M('sector');
      $data = $sector->select();
      return $this->getchildids1($data,$sectorid);
   }


   public function getchildids1($data,$sectorid){
      static $arrid=array();
      $arrid[]=$sectorid;
      foreach ($data as $key => $value) {
         if ($value['parent_sector'] == $sectorid && $value['sector_id'] !=  $sectorid) {//找子类
            $arrid[]=$value['sector_id'];
            $this->getchildids1($data,$value['sector_id']);
         }
      }
      return array_unique($arrid);
   }

  // 获得下属部门
   public function get_child(){
      $uinfo = UserModel::loadFromSession();
      $sectorid = $uinfo['sector_id'];
      $sector =  M('sector');
      $res = $sector->where('sector_id = '.$sectorid)->find();
      if ($res['parent_sector'] == 1 ) {
        $data = $sector->select();
        return $this->get_childids($data,$sectorid);  
      }elseif($sectorid!=1 && $res['parent_sector'] != 1){
        $data = $sector->select();
        return $this->get_childids_($data,$sectorid);     
      }elseif ($sectorid == 1) {
        $data = $sector->select();
        return $this->get_childids_1($data,$sectorid);  
      }
   }

  //当时总监以上的职位的时候 
   public function get_childids($data,$sectorid){
    static $arrid=array();
      $arrid['sector_id'][]=$sectorid; 
      $arrid['state'][0]='k';  
      foreach ($data as $key => $value) {
         if ($value['parent_sector'] == $sectorid && $value['sector_id'] !=  $sectorid) {//找子类
          if ($value['parent_sector'] == $arrid['sector_id'][0]) {
            $arrid['state'][]='a';    
          }else{
            $arrid['state'][]=$sectorid;                       
          }
          $this->get_childids($data,$value['sector_id']);
         }
      }
      return $arrid;        
   }
   // 当是admin的时候
   public function get_childids_1($data,$sectorid){
      static $arrid=array();
      $arrid['sector_id'][]=$sectorid; 
      $arrid['state'][0]='s';   
      foreach ($data as $key => $value) {
         if ($value['parent_company'] == $sectorid && $value['sector_id'] !=  $sectorid) {//找子类
          if ($value['parent_company'] == $arrid['sector_id'][0]) {//用两个数组将你的部门和你的下属部门的关系表现出来
            $arrid['state'][]='a';    
          }else{
            $arrid['state'][]=$sectorid;                      
          }
          $this->get_childids_1($data,$value['sector_id']);
         }
      }
      return $arrid;        
   }

  //当不是总监及以上的职位的时候 
   public function get_childids_($data,$sectorid){
      static $arrid=array(0=>'m');
      $arrid[]=$sectorid;  
      foreach ($data as $key => $value) {
         if ($value['parent_sector'] == $sectorid && $value['sector_id'] !=  $sectorid) {//找子类
            $arrid[]= $value['sector_id'];        
            $this->get_childids_($data,$value['sector_id']);
         }
      }
        return array_unique($arrid);     
   }


   // 获得用户id
   public function getR(){
      $uinfo = UserModel::loadFromSession();
      $uid = $uinfo['user_id'];
      return $uid;      
   }

   // 获得用户岗位及其下属
   public function getrole(){
      $uinfo = UserModel::loadFromSession();
      $roleid = $uinfo['role_id'];
      $role =  M('role');
      $data = $role->select();
      return $this->getroles($data,$roleid);  
   }


   public function getroles($data,$roleid){
      static $attid=array();
      $attid[]=$roleid;
      foreach ($data as $key => $value) {
         if ($value['parent_role'] == $roleid && $value['role_id'] != $roleid) {//找子类
            $attid[]=$value['role_id'];
            $this->getroles($data,$value['role_id']);
         }
      }
      return array_slice(array_unique($attid), 1);
   }

  // 添加OM配置
  public function add_om($addname,$addaddress,$addIP,$port,$addrec,$addlist,$addads,$addport,$addcname,$addpas,$database){
    $uinfo = UserModel::loadFromSession();
    $userId = $uinfo['user_id'];
    $r = array('d'=>NULL,'i'=>'','r'=>0);
    if( !$uinfo )
      $r['i'] = '加载用户信息失败';
    else{
        $OServer = M('om_server');
        $sector =  M('sector');
        $subcom1 = $sector ->join('user ON sector.sector_id = user.sector_id')
                  ->where('user.user_id = '.$userId)
                  ->find();
        $d= array();
        $d['name']=$addname;
        $d['ipaddr']=$addaddress;
        $d['serverip']=$addIP;
        $d['serviceport']=$port;
        $d['mp3_server']=$addrec;
        $d['mp3_dir']=$addlist;
        $d['dbhost']=$addads;
        $d['dbport']=$addport;
        $d['dbname']=$database;
        $d['dbuser']=$addcname;
        $d['dbpsw']=$addpas;
        $d['lasttime']=date('Y-m-d H:i:s');
        $d['sub_company']=$subcom1['parent_company'];
        $addID = $OServer->add( $d );
        if( $addID ){
          $r['r'] = $addID ;
          $r['i'] = 'OK';
          $r['d'] = $OServer->where( 'omid='.$addID )->find();
        }else{
          $r['i'] = '保存失败';
        }      
    }

    return $r;
  }

 // 编辑OM配置
 public function editom($id,$addname1,$addaddress1,$addIP1,$port1,$addrec1,$addlist1,$addads1,$addport1,$addcname1,$addpas1,$database1){
    $uinfo = UserModel::loadFromSession();
    $userId = $uinfo['user_id'];
    $r = array('d'=>NULL,'i'=>'','r'=>0);
    if( !$uinfo ){
      $r['i'] = '加载用户信息失败';
      return $r;
    }

    $OServer = M('om_server');
    $d= array();
    $d['omid'] = $id;
    $d['name']=$addname1;
    $d['ipaddr']=$addaddress1;
    $d['serverip']=$addIP1;
    $d['serviceport']=$port1;
    $d['mp3_server']=$addrec1;
    $d['mp3_dir']=$addlist1;
    $d['dbhost']=$addads1;
    $d['dbport']=$addport1;
    $d['dbname']=$database1;
    $d['dbuser']=$addcname1;
    $d['dbpsw']=$addpas1;
    $d['lasttime']=date('Y-m-d H:i:s');
    $editRtn = $OServer->save($d);
    if ($editRtn) {
      $r['r'] = 1;
      $r['m'] = "用户编辑成功！";
      $r['data'] = $OServer->where("omid=".$id)->find();
    }else{  
      $r['m'] = "很抱歉，用户编辑失败！";
    }   
    return $r;  

  }

  // 获取所属公司OM
  public function GOM(){
      $uinfo = UserModel::loadFromSession();
      $sectorid = $uinfo['sector_id'];
      $rback  =  M('om_server') -> field('omid,name') 
                      -> join('sector ON om_server.sub_company = sector.parent_company')
                      -> where('sector.sector_id ='.$sectorid)
                      ->select();
      $arr = array();
      foreach ($rback as $k => $v) {
        if ($k == 0) {
          $arr[$k]['k'] = "0";
          $arr[$k]['v'] = '全部';
          $arr[$k]['m'] = 0;
          $arr[$k]['cs'] = '';
        }
        $arr[$k+1]['k'] = $v['omid'];
        $arr[$k+1]['v'] = $v['name'];
        $arr[$k+1]['m'] = $k+1;//多加一个字段,否则id和标识符不会区分开。选择错误
        $arr[$k+1]['cs'] = '';
      }
      return $arr;
  }

// 获得部门及下属部门
  public function getadmin(){
        $rchild = $this->getchild();
        $User = M('user');
        $arr = array();
        $arr['sector_id'] = array('in',$rchild);
        $res = $User->field('user_id')->where($arr)->select();
        return $res;
  }

 //添加分机配置
  public function addcon($bindperson,$subtelphone,$add_device){
    $uinfo = UserModel::loadFromSession();
    $userId = $uinfo['user_id'];
    $r = array('d'=>NULL,'i'=>'','r'=>0);
    if( !$uinfo )
      $r['i'] = '加载用户信息失败';
    else{
      $omse = M('om_server');
      $User = M('user');
      $omsub  = M('om_subphone');
      $a = array();
      $att = $arr = array();
      $a['nickname']=$bindperson;
      $reuse = $User->where($a)->find();
      if (!$reuse) {
        $r['i']='输入员工不存在';
        return $r;
      }
      $arr['admin_no']=$reuse['user_id'];//只要是在OM配置中出现过。就不能用了
      // $arr['omid'] = $add_device;
      $att['subphone']=$subtelphone;//只要是在OM配置中出现过。就不能用了，而不是说在一个配置中出现过就不能用。
      // $att['omid']=$add_device;
      $reom = $omsub ->where($arr)->find();
      $resub = $omsub ->where($att)->find();
      if ( !$reom && !$resub) {
        $d = array();
        $d['omid'] = $add_device;
        $d['admin_no'] = $reuse['user_id'];
        $d['subphone'] = $subtelphone;
        $rback = $omsub ->add($d);
        if ($rback) {
            $r['r'] = 1 ;
            $r['i'] = 'OK';
            $r['d'] = $omsub->field('user.nickname,om_subphone.subphone,om_server.name')
                            ->join('user ON om_subphone.admin_no = user.user_id')
                            ->join('om_server ON om_subphone.omid = om_server.omid')
                            ->where('om_subphone.id = '.$rback)
                            ->find();
          }else{
            $r['i'] = '保存失败';        
        }
      }else{
          $r['r'] = '' ;
          $r['i'] = '信息已存在,请重新核实';
      }
      return $r;

    }    
  }

  // 获得所属设备
  public function getdev(){
      $oms = M('om_server');
      $res = $oms -> field('omid,name')->select();
      return $res;
  }

  //编辑分机设备
  public function editcon($id,$bindperson1,$subtelphone1,$add_device1){
    $uinfo = UserModel::loadFromSession();
    $r = array('d'=>NULL,'i'=>'','r'=>0);
    if( !$uinfo ){
      $r['i'] = '加载用户信息失败';
      return $r;
    }
      $omse = M('om_server');
      $User = M('user');
      $omsub  = M('om_subphone');
      $a = $att = $arr = array();
      $a['nickname']=$bindperson1;
      $reuse = $User->where($a)->find();
      if (!$reuse['user_id']) {
          $r['i'] = '员工名输入错误,请重新核实';
          return $r;
      }

      $arr['admin_no']=$reuse['user_id'];
      // $arr['omid'] = $add_device1;
      $att['subphone']=$subtelphone1;
      // $att['omid']=$add_device1;
      $reom = $omsub ->where($arr)->find();
      $resub = $omsub ->where($att)->find();
      if (!$reom || !$resub){
        $d = array();
        $d['id'] = $id;
        $d['omid'] = $add_device1;
        $d['admin_no'] = $reuse['user_id'];
        $d['subphone'] = $subtelphone1;
        $rback = $omsub ->save($d);
        if ($rback) {
            $r['r'] = 1 ;
            $r['i'] = 'OK';
            $r['d'] = $omsub->field('user.nickname,om_subphone.subphone,om_server.name,om_subphone.id')
                            ->join('user ON om_subphone.admin_no = user.user_id')
                            ->join('om_server ON om_subphone.omid = om_server.omid')
                            ->where('om_subphone.id = '.$id)
                            ->find();
          }else{
            $r['i'] = '保存失败';        
        }
      }else{
          $r['r'] = '' ;
          $r['i'] = '信息已存在,请重新核实';
      } 

      return $r;
  }

  // om话务管理时间转换
  public function trans($res){
    foreach ($res as $k => $v) {
      if ($v['calltime']) {
        $v['calltime'] = $this->Sec2Time($v['calltime']);
      }
      $res[$k]=$v;
    }
    return $res;
  } 

  //秒数转换成时分秒格式
   public function Sec2Time($time){
      if($time == 0) $t = 0;
      else $t = floor($time/60);
      return $t;   
     }

     //获取本周起止时间
    public function getWeek(){
      //当前日期  
      $sdefaultDate = date("Y-m-d");  
      //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期  
      $first = 1;  
      //获取当前周的第几天 周日是 0 周一到周六是 1 - 6  
      $w = date('w',strtotime($sdefaultDate));  
      //获取本周开始日期，如果$w是0，则表示周日，减去 6 天  
      $week_start = date('Ymd',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));  
      //本周结束日期  
      $week_end = date('Ymd',strtotime("$week_start +6 days"));

        return array($week_start,$week_end);
  }

    //获取本周每天对应日期
    public function getWeekDay($type){
      //当前日期  
      $sdefaultDate = date("Y-m-d");  
      //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期  
      $first = 1;  
      //获取当前周的第几天 周日是 0 周一到周六是 1 - 6  
      $w = date('w',strtotime($sdefaultDate));  
      //获取本周开始日期，如果$w是0，则表示周日，减去 6 天  
      $week_start = date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));  
      //本周结束日期  
      $week_end = date('Y-m-d',strtotime("$week_start +6 days"));

      for($j = strtotime($week_start);$j <= strtotime($week_end);$j+=86400){
        $week_show[] = date("Y-m-d",$j);
        $week_show_2[] = date("Ymd",$j);
      }
      if($type == "addok"){
         return $week_show;
      }else return $week_show_2;
       
    }
    //获取本月起止对应日期
    public function getMonthDay($date){
      return array(
        'month_start_day' => date("Ymd",mktime(0, 0 , 0,date("m"),1,date("Y"))),
        'month_end_day' => date("Ymd",mktime(23,59,59,date("m"),date("t"),date("Y")))
        );
    }

    // 获取部门职位权限
    public function cs(){
      $sector1 = M('sector');
      $arr = $att = $ass = array();
      $uinfo = UserModel::loadFromSession();
      $sector = $uinfo['sector_id'];
      $arr['parent_sector'] = 1;
      $res = $sector1->field('sector_id')->where($arr)->select();
      $rbk = $sector1->where('sector_id ='.$sector)->find();
      $ps = $rbk['parent_sector'];
      foreach ($res as $k => $v) {
          $att[] = $v['sector_id'];
      }
      if (in_array($ps,$att) || $sector == 1 || $ps == 1) {//如果是admin 总经理 总监 部门经理的区分
        if ($sector == 1) {
              $sec = $sector1->field('sector_id')->where('parent_sector ='.$sector)->select();
              foreach ($sec as $k1 => $v1) {
                $ass[] = $v1['sector_id'];
              }
            $ak = $ass[0]; 
            return array($ak,1,3);//去admin的子类
        }else{
            return array(0,1);
        }
      }else{
        return array($sector,2); 
      }     
    }

}
